/** @file:工具文件 */
import {
	Loading
} from 'element-ui';
import md5 from 'js-md5';
import Qs from 'qs';
import vue from '../main';

let loading;
let loadingCount = 0;

function start() {
	loading = Loading.service({
		lock: true,
		spinner: 'el-icon-loading',
		text: '加载中...',
		background: 'rgba(0,0,0,0.7)'
	})
};

function end() {
	loading.close();
}

export function showLoaing() {
	if (loadingCount == 0) {
		start();
	};
	loadingCount++
};

export function hideLoading() {
	loadingCount--;
	if (loadingCount == 0) {
		end()
	}
}

// 计算百分比
export function GetPercent(num, total) {
	/// <summary>
	/// 求百分比
	/// </summary>
	/// <param name="num">当前数</param>
	/// <param name="total">总数</param>
	num = parseFloat(num);
	total = parseFloat(total);
	if (isNaN(num) || isNaN(total)) {
		return "-";
	}
	return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00) + "%";
}

/**重置message，防止重复点击重复弹出message弹框 */
import {
	Message
} from 'element-ui';
let messageInstance = null;
const resetMessage = (options) => {
	if (messageInstance) {
		messageInstance.close();
	}
	messageInstance = Message(options);
};
['error', 'success', 'info', 'warning'].forEach(type => {
	resetMessage[type] = options => {
		if (typeof options === 'string') {
			options = {
				message: options
			}
		}
		options.type = type
		return resetMessage(options)
	}
})
export const customMessage = resetMessage;

// 上传图片公共参数
export const uploadParams = () => {
	let time = parseInt(new Date().getTime() / 1000);
	let user_id = localStorage.getItem('user_id') || '';
	let token = localStorage.getItem('token') || '';
	let sign = md5(user_id + token + time + md5('huankemao'));
	return {
		time,
		user_id,
		token,
		sign
	}
};

// 解决预览图片点击model无法关闭的问题
export const createImgClose = () => {
	vue.$nextTick(() => {
		// 获取遮罩层dom
		let domImageMask = document.querySelector(".el-image-viewer__mask");
		if (!domImageMask) {
			return;
		}
		domImageMask.addEventListener("click", (e) => {
			// 点击遮罩层时调用关闭按钮的 click 事件
			document.querySelector(".el-image-viewer__close") ?
				document.querySelector(".el-image-viewer__close").click() :
				"";
			e.stopPropagation();
		});
	});
};


// 输入正整数
export const isnumber = (val) => {
	val = val.replace(/[^0-9]/gi, "");
	val <= 0 ? val = '' : '';
	// 此处还可以限制位数以及大小
	return Number(val);
};
